// 详情
var PPurchaseDetail = {
    uList: '/pPurchaseDetail/list'
    , orderStatus: 0
    , unitArr: []
    , purchaseId: 0,
    editIndex: -1,
    isDg: 0,
};

// 详情按钮
PPurchaseDetail.btn = function () {
    if (PPurchaseDetail.orderStatus == 0) {
        var sb = new $yd.SearchBtn($(PPurchaseDetail.obtn));
        sb.create('plus', '入库', PPurchaseDetail.inRepository);
    }
};

// 详情的表格
PPurchaseDetail.dg = function () {

    PPurchaseDetail.dtable.datagrid({
        url: "/mSales/detailListTable?saleId=" + PPurchaseDetail.purchaseId,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,

        columns: [[
            {field: 'wearhouseId', hidden: true},//仓库
            {field: 'positionId', hidden: true},//库位
            {field: 'skusId', checkbox: false, hidden: true},//规格id
            {field: 'goodsName', title: '商品名称', width: 150},
            {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
            {field: 'skus', title: '规格', width: 200},
            {field: 'code', title: '商品编号', width: 80},
            {field: 'amount', title: '参考售价', width: 80},
            {
                field: 'amountActual',
                title: '<span style="color:deeppink">实际售价</span>',
                width: 80,
                editor: {type: 'numberbox', options: {required: true, min: 0, precision: 2}}
            },
            {
                field: 'count',
                title: '<span style="color:deeppink">数量</span>',
                width: 80,editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },
            {
                field: 'shouldPay', title: '总额', width: 80, formatter: function (value, row, index) {
                    var all = accMul(Number(row.count),Number(row.amountActual))
                    return all.toFixed(2);
                }
            }
        ]],
        onClickCell: function (index, field) {
            var orderStatus = $('#orderStatus').val();
            if(orderStatus != 0) {
                var eaRows = PPurchaseDetail.dtable.datagrid('getRows');
                $(eaRows).each(function (index, item) {
                    PPurchaseDetail.dtable.datagrid('endEdit', index);
                });
                return;
            }
            if (PPurchaseDetail.editIndex != index) {
                if (PPurchaseDetail.editIndex > -1) {
                    PPurchaseDetail.dtable.datagrid('endEdit', PPurchaseDetail.editIndex);
                }
                PPurchaseDetail.editIndex = index;
            }

            if ( field == "amountActual" || field == "count" ) {
                PPurchaseDetail.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {
            if (changes) {
                PPurchaseDetail.dtable.datagrid('updateRow', {
                    index: index,
                    row: {
                        shouldPay: Number(row.amountActual) * Number(row.count),
                    }
                });

                var rows = PPurchaseDetail.dtable.datagrid("getRows");
                var shouldPay = 0;
                for (var i = 0; i < rows.length; i++) {
                    var  tmp = accMul(Number(rows[i]['count']),Number(rows[i]['amountActual']))
                    shouldPay = shouldPay +tmp
                }
                $('#totalMoney').val(shouldPay.toFixed(2));
            }
        }
    });
    PPurchaseDetail.dtable.datagrid('enableCellEditing');
};
function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//入库
PPurchaseDetail.inRepository = function () {
    $yd.confirm(function () {
        //入库保存数据
        $yd.post("/pPurchase/inRepository", {purchaseId: PPurchaseDetail.purchaseId}, function (data) {
            $yd.alert("操作成功", function () {
                window.location.reload();
            });
        });
    });
};
PPurchaseDetail.endEditAll = function () {
    var rows = PPurchaseDetail.dtable.datagrid("getRows");
    var shouldPay = 0;
    for (var i = 0; i < rows.length; i++) {
        var  tmp = accMul(Number(rows[i]['count']),Number(rows[i]['amountActual']));
        shouldPay = shouldPay + tmp
    }
    $('#totalMoney').val(shouldPay);
}

// 结算记录
PPurchaseDetail.dg2 = function () {
    PPurchaseDetail.ptable = $('#pay_table');
    PPurchaseDetail.ptable.datagrid({
        url: "/pPurchaseDetail/payList?purchaseId=" + PPurchaseDetail.purchaseId,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        columns: [[
            {field: 'ctime', title: '日期', width: 80},
            {field: 'amount', title: '本次付款', width: 80},
            {field: 'remain_amount', title: '剩余未结算', width: 80},
            {field: 'type_name', title: '结算方式', width: 80},
            {field: 'username', title: '操作人', width: 80},
            {field: 'remark', title: '备注', width: 80}
        ]]
    });
};

PPurchaseDetail.changePayFee = function(newValue,oldValue) {
    if(newValue == "") {
        $("#payFee").numberbox("setValue", 0);
        return;
    }
    if(Number(newValue) > Number($("#amountIng").val())) {
        $yd.alert("本次付款金额不能大于剩余待付！", function () {
            $("#payFee").numberbox("setValue", $("#amountIng").val());
        });
    }
};

// 保存结算信息
PPurchaseDetail.pay = function () {
    var payFee = $("#payFee").val();
    var payType = $("#payType").val();
    var payRemark = $("#payRemark").val();
    if(Number(payFee) == 0) {
        $yd.alert("付款金额不能为0");
        return;
    }

    $.post("/pPurchase/pay",{
        purchaseId: PPurchaseDetail.purchaseId,
        payType: payType,
        payFee: payFee,
        payRemark: payRemark
    },function (data) {
        if(data.code == 0) {
            $yd.alert("支付成功", function () {
                window.location.reload();
            });
        }
    });
};
PPurchaseDetail.mouseClick = function(e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (PPurchaseDetail.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
        if (PPurchaseDetail.editIndex != -1) {
            PPurchaseDetail.dtable.datagrid('endEdit', PPurchaseDetail.editIndex);
            PPurchaseDetail.editIndex = -1;
        }
    }
};
$(function () {
    
    document.onclick = PPurchaseDetail.mouseClick;
    PPurchaseDetail.orderStatus = $("#orderStatus").val();
    PPurchaseDetail.purchaseId = $("#purchaseId").val();

    PPurchaseDetail.dtable = $('#pPurchaseDetail_table');
    PPurchaseDetail.obtn = '#pPurchaseDetail_btn';
    PPurchaseDetail.btn(); // 初始化按钮
    PPurchaseDetail.dg(); // 采购详情数据表格

    PPurchaseDetail.dg2(); // 结算记录数据表格

    $("input[name='payType']").combobox({
        url: "/sysDict/pay_type",
        panelHeight:'auto',
        editable:false,
        required:true,
        valueField:'id',
        textField:'text',
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });
    //监听input
    $('#realPay').bind('input propertychange', function() {
        var totalMoney = $('#totalMoney').val();
        var realPay = $('#realPay').val();
        var status = $('#payStatusCommit').val();
        if (status == 0){
            // if (Number(totalMoney) > Number(realPay)){
            //     document.getElementById("endCountButton").innerHTML="保存";
            //     document.getElementById("endCountButton").style.backgroundColor = '#FD9900';
            // }else {
            //     document.getElementById("endCountButton").innerHTML="结算";
            //     document.getElementById("endCountButton").style.backgroundColor = 'pink';
            // }
        }
    });

    $("input[name='orderStatus']").combobox({
        url: "/sysDict/purchase_next_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            if ($('#settle').val() == 1) {
                $(this).combobox("setValue", d[1].value);
            }else {
                $(this).combobox("setValue", d[0].value);
            }
        },
        onChange: function (value) {
            // if (value == 1) {
            //     document.getElementById("endCountButton").innerHTML="结算";
            //     document.getElementById("endCountButton").style.backgroundColor = 'pink';
            // }
            // var totalMoney = $('#totalMoney').val();
            // var realPay = $('#realPay').val();
            // if ((Number(totalMoney) > Number(realPay)) && value ==0) {
            //     if (document.getElementById("endCountButton") !=null && document.getElementById("endCountButton")!= undefined) {
            //         document.getElementById("endCountButton").innerHTML="保存";
            //         document.getElementById("endCountButton").style.backgroundColor = '#FD9900';
            //     }
            // }
        }
    });
});


PPurchaseDetail.inRepositoryBtn = function () {
    PPurchaseDetail.endEditAll();
    $yd.confirm("出库将生产相应的出库单，结算信息，是否确认出库？",function () {
        //出库保存数据
        var rows = $('#pPurchaseDetail_table').datagrid("getRows");
        rows = JSON.stringify(rows);
        var realPay = $('#realPay').val();
        var remark = $('#remark').val();
        var payStatus = $('#payStatusCommit').val();
        var totalMoney = $('#totalMoney').val();
        $yd.post("/mSales/outRepositoryFromWindow", {saleId: PPurchaseDetail.purchaseId,rows:rows,realPay:realPay,
            totalMoney:totalMoney,payStatus:payStatus,remark:remark}, function (data) {
            $yd.alert("操作成功", function () {
                window.location.reload();
            });
        });
    });
};

PPurchaseDetail.endCount = function () {
    $yd.confirm("确认对此销售单进行结算？",function () {
        //结算保存数据
        var realPay = $('#realPay').val();
        var payStatus = $('#payStatusCommit').val();
        var remark = $('#remark').val();
        var totalMoney = $('#totalMoney').val();
        $yd.post("/mSales/endCountSale", {saleId: PPurchaseDetail.purchaseId,realPay:realPay,totalMoney:totalMoney,
            payStatus:payStatus,remark:remark}, function (data) {
            $yd.alert("操作成功", function () {
                window.location.reload();
            });
        });
    });
};

PPurchaseDetail.cancelIn = function () {
    $yd.confirm("确认撤回此单的出库、结算状态，回到未出库、未结算状态？",function () {
        $yd.post("/mSales/cancelOutSale", {saleId: PPurchaseDetail.purchaseId}, function (data) {
            $yd.alert("操作成功", function () {
                window.location.reload();
            });
        });
    });
};

PPurchaseDetail.cancelPurchaseEnd = function () {
    $yd.confirm("确认撤回此销售单的结算数据，回到未结算状态？",function () {
        $yd.post("/mSales/cancelSaleEnd", {saleId: PPurchaseDetail.purchaseId}, function (data) {
            $yd.alert("操作成功", function () {
                window.location.reload();
            });
        });
    });
};


//入库按钮
var inBtn = document.getElementById("inRepositoryButton");
if (inBtn != null) {
    inBtn.addEventListener("click", function () {
        PPurchaseDetail.inRepositoryBtn();
    });
}
//结算按钮
var endCountBtn = document.getElementById("endCountButton");
if (endCountBtn != null) {
    endCountBtn.addEventListener("click", function () {
        PPurchaseDetail.endCount();
    });
}

//撤销入库按钮
var cancelInButton = document.getElementById("cancelInButton");
if (cancelInButton != null) {
    cancelInButton.addEventListener("click", function () {
        PPurchaseDetail.cancelIn();
    });
}

//撤销结算按钮
var cancelPurchaseEnd = document.getElementById("cancelPurchaseEnd");
if (cancelPurchaseEnd != null) {
    cancelPurchaseEnd.addEventListener("click", function () {
        PPurchaseDetail.cancelPurchaseEnd();
    });
}